<!DOCTYPE html>
<html lang="zh">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>与 Ollama 交互</title>
    <style>
        body {
            font-family: Arial, sans-serif;
        }
        #messages {
            border: 1px solid #ccc;
            padding: 10px;
            max-height: 300px;
            overflow-y: auto;
        }
        #inputMessage {
            width: 100%;
            padding: 10px;
            margin-top: 10px;
            box-sizing: border-box;
        }
        #sendButton {
            margin-top: 10px;
            padding: 10px 20px;
            background-color: #4CAF50;
            color: white;
            border: none;
            cursor: pointer;
        }
        #sendButton:hover {
            background-color: #45a049;
        }
    </style>
</head>
<body>
    <h1>与 Ollama 交互</h1>
    <div id="messages"></div>
    <textarea id="inputMessage" placeholder="输入你的消息..." rows="3"></textarea>
    <button id="sendButton">发送</button>

    <script>
        const sendButton = document.getElementById('sendButton');
        const inputMessage = document.getElementById('inputMessage');
        const messages = document.getElementById('messages');

        // Ollama 服务的 URL，假设它运行在本机的 11434 端口
        const ollamaApiUrl = 'http://localhost:11434/api/chat';

        sendButton.addEventListener('click', async () => {
            const message = inputMessage.value.trim();
            if (!message) return;

            // 显示用户发送的消息
            addMessage('你：' + message);

            try {
                const response = await fetch(ollamaApiUrl, {
                    method: 'POST',
                    headers: {
                        'Content-Type': 'application/json',
                    },
                    body: JSON.stringify({
                        model: 'deepseek-r1:1.5b',
                        messages: [
                            { role: 'user', content: message }
                        ],
                        stream: false
                    })
                });

                if (response.ok) {
                    const data = await response.json();
                    const reply = data.message && data.message.content ? data.message.content : '无回复内容';
                    addMessage('Ollama：' + reply);
                } else {
                    addMessage('错误：无法与 Ollama 服务通信');
                }
            } catch (error) {
                addMessage('错误：' + error.message);
            }

            inputMessage.value = '';  // 清空输入框
        });

        function addMessage(text) {
            const messageDiv = document.createElement('div');
            messageDiv.textContent = text;
            messages.appendChild(messageDiv);
            messages.scrollTop = messages.scrollHeight; // 滚动到底部
        }
    </script>
</body>
</html>